<?php

namespace app\modules\merchant\services;

use app\common\services\BaseService;
use app\components\pagination\Pagination;
use app\models\Goods;
use app\modules\merchant\forms\attribute\AttributeForm;
use app\modules\merchant\forms\goods\GoodsAttributeForm;
use app\modules\merchant\forms\goods\GoodsForm;
use yii\helpers\ArrayHelper;

class GoodsService extends BaseService {

    /**
     * 搜索
     * @param $merchant_id
     * @param $goods_name
     * @param $cat_id
     * @param $is_sale
     * @param $page
     * @param $pagesize
     * @return array|\yii\db\ActiveRecord[]
     */
    public static function search($merchant_id,$goods_name,$cat_id,$is_sale,&$page,$pagesize){
        $query = Goods::find()->orderBy(['sort'=>SORT_ASC]);

        if(!empty($merchant_id)){
            $query->andWhere(['merchant_id'=>$merchant_id]);
        }
        if(!empty($goods_name)){
            $query->andWhere(['like','goods_name',$goods_name]);
        }
        if(!empty($cat_id)){
            $query->andWhere(['cat_id'=>$cat_id]);
        }
        if(!empty($is_sale)){
            $query->andWhere(['is_sale'=>$is_sale]);
        }

        $page = new Pagination(['totalCount' => $query->count(), 'pageSize' => $pagesize]);
        $query->offset($page->getOffset());
        $query->limit($page->getLimit());

        return $query->all();
    }

    /**
     * 创建
     * @param GoodsForm $goods_form
     * @return bool
     * @throws \Throwable
     */
    public static function create(GoodsForm $goods_form){
        if(!$goods_form->validate()){
            self::setError($goods_form->getFirstFieldError());
            return false;
        }

        $transaction = \Yii::$app->getDb()->beginTransaction();

        $goods_model = new Goods();
        $goods_model->setAttributes($goods_form->getAttributes(),false);
        $goods_model->setAttribute("cat_name",GoodsCategoryService::getInfoById($goods_form->merchant_id,$goods_form->cat_id)->cat_name);
        $goods_model->setAttribute("add_time",date("Y-m-d H:i:s"));
        if(!$goods_model->insert()){
            $transaction->rollBack();
            return false;
        }
        //属性
        if(empty($goods_form->attr_item)){
            $transaction->commit();
            return true;
        }
        foreach($goods_form->attr_item as $v){
            $attr_form = new AttributeForm();
            $attr_form->load($v,'');
            $attr_form->merchant_id=$goods_form->merchant_id;
            $attr_form->goods_id=$goods_model->goods_id;
            if(!$attr_model = AttributeService::create($attr_form)){
                self::setError(AttributeService::getError());
                $transaction->rollBack();
                return false;
            }

            foreach($v['goods_attr'] as $vv){
                $goods_attr_form = new GoodsAttributeForm();
                $goods_attr_form->load($vv,'');
                $goods_attr_form->goods_id = $goods_model->goods_id;
                $goods_attr_form->attr_id = $attr_model->attr_id;
                if(!GoodsAttributeService::create($goods_attr_form)){
                    self::setError(GoodsAttributeService::getError());
                    $transaction->rollBack();
                    return false;
                }
            }
        }
        $transaction->commit();
        return true;
    }

    /**
     * 更新
     * @param GoodsForm $goods_form
     * @return bool
     * @throws \Throwable
     * @throws \yii\db\StaleObjectException
     */
    public static function update(GoodsForm $goods_form){
        if(!$goods_form->validate()){
            self::setError($goods_form->getFirstFieldError());
            return false;
        }

        $transaction = \Yii::$app->getDb()->beginTransaction();

        $goods_model = Goods::findOne(['merchant_id'=>$goods_form->merchant_id,'goods_id'=>$goods_form->goods_id]);
        if(!$goods_model){
            self::setError(\Yii::t("app","商品不存在"));
            return false;
        }
        if($goods_form->cat_id != $goods_model->cat_id){
            $goods_model->setAttribute("cat_name",GoodsCategoryService::getInfoById($goods_form->merchant_id,$goods_form->cat_id)->cat_name);
        }
        $goods_model->setAttributes($goods_form->getAttributes(),false);
        if($goods_model->update() === false){
            $transaction->rollBack();
            return false;
        }

        //清空属性
        AttributeService::delete($goods_model->merchant_id,$goods_model->goods_id);

        //属性
        if(empty($goods_form->attr_item)){
            $transaction->commit();
            return true;
        }

        foreach($goods_form->attr_item as $v){
            $attr_form = new AttributeForm();
            $attr_form->load($v,'');
            $attr_form->merchant_id=$goods_form->merchant_id;
            $attr_form->goods_id=$goods_model->goods_id;
            if(!$attr_model = AttributeService::create($attr_form)){
                self::setError(AttributeService::getError());
                $transaction->rollBack();
                return false;
            }

            foreach($v['goods_attr'] as $vv){
                $goods_attr_form = new GoodsAttributeForm();
                $goods_attr_form->load($vv,'');
                $goods_attr_form->goods_id = $goods_model->goods_id;
                $goods_attr_form->attr_id = $attr_model->attr_id;
                if(!GoodsAttributeService::create($goods_attr_form)){
                    self::setError(GoodsAttributeService::getError());
                    $transaction->rollBack();
                    return false;
                }
            }
        }
        $transaction->commit();
        return true;
    }

    /**
     * 获取信息
     * @param $merchant_id
     * @param $id
     * @return array|\yii\db\ActiveRecord|null
     */
    public static function getInfoById($merchant_id,$id)
    {
        $model = Goods::find()
            ->asArray(true)
            ->where(['merchant_id'=>$merchant_id,'goods_id'=>$id])
            ->one();
        if(!$model){
            return null;
        }
        //属性
        $attr_item = GoodsAttributeService::search($model['goods_id']);
        if(empty($attr_item)){
            $model['attr_item'] = [];
            return $model;
        }
        $attr_item = ArrayHelper::index($attr_item,null,"attr_id");
        foreach($attr_item as $k=>$v){
            $attr = AttributeService::getInfoById($model['merchant_id'],$model['goods_id'],$k);
            if(empty($attr)){
                continue;
            }
            $model['attr_item'][] = ['attr_id'=>$attr->attr_id,'attr_name'=>$attr->attr_name,'goods_attr'=>$attr_item[$k]];
        }
        return $model;
    }

    /**
     * 删除
     * @param $merchant_id
     * @param $id
     */
    public static function delete($merchant_id,$id)
    {
        Goods::deleteAll(['merchant_id'=>$merchant_id,'goods_id'=>$id]);
    }
}